package com.work.formaldehyde.homefragment;

import android.Manifest;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.mancj.slimchart.SlimChart;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.MainActivity;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activity.CityManageActivity;
import com.work.formaldehyde.activity.JianCeActivity;
import com.work.formaldehyde.activity.JianCeListActivity;
import com.work.formaldehyde.activity.MsgListActivity;
import com.work.formaldehyde.activity.ShangPingActivity;
import com.work.formaldehyde.lunch.LunchActivity;
import com.work.formaldehyde.model.AqiModel;
import com.work.formaldehyde.model.CityManageModel;
import com.work.formaldehyde.model.HourModel;
import com.work.formaldehyde.model.SixModel;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;
import com.work.formaldehyde.view.CircleProgress;
import com.work.formaldehyde.view.WeatherChartView;
import com.work.formaldehyde.view.WeatherItemView;
import com.work.formaldehyde.view.WeatherModel;
import com.work.formaldehyde.view.ZzWeatherView;
import com.work.formaldehyde.zzweatherview.AirLevel;
import com.work.formaldehyde.zzweatherview.WeatherModels;
import com.work.formaldehyde.zzweatherview.ssWeatherView;
import com.xujiaji.happybubble.BubbleDialog;
import com.xujiaji.happybubble.BubbleLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import io.reactivex.functions.Consumer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import pl.droidsonroids.gif.GifImageView;

public class TianqiFragment extends Fragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, View.OnTouchListener {
    //用于获取视图
    private View root;
    private LinearLayout top_layout;
    private String date, aqi, pm25, humidity, wind_speed, temperature, primary_pollutant, quality;
    String[] locationPermission = {Manifest.permission.ACCESS_FINE_LOCATION};
    private GifImageView gif;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //定位权限
            if (ContextCompat.checkSelfPermission(getActivity(), locationPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                requestPermissions(locationPermission, 300);
            }
        }
        root = inflater.inflate(R.layout.fragment_tianqi, container, false);//初始加载
        nointe(root);
        if (ApiUtils.isNetworkConnected(getActivity()))
            InitView(root);
        return root;
    }


    /**
     * 所有需要的权限类型
     */
    private static final String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION};
    private static final int PERMISSION_REQUEST_CODE = 1;

    /**
     * 动态获取权限
     */
    public void getPermission() {
        RxPermissions rxPermissions = new RxPermissions(getActivity());
        rxPermissions.request(PERMISSIONS).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean granted) throws Exception {
                if (granted) {
                    Toast.makeText(getActivity(), "成功", Toast.LENGTH_LONG);
                    //权限申请成功

                } else {
                    swipeLayout.setRefreshing(false);
                    //权限申请不成功，弹窗提示退出
                    Toast.makeText(getActivity(), "请开起定位服务后，再次刷新", Toast.LENGTH_LONG);
                }
            }
        });
    }

    private int cityindex = -1;

    private WeatherChartView chartView;//天气折线视图
    private TextView location_text, tianqi_good_text, home_time, start_num_text, end_num_text, rc_time, rl_time;//首页定位信息textview
    private SlimChart slimChart;//环形图
    private CircleProgress mCircleProgress1;
    private Random mRandom;
    public static SwipeRefreshLayout swipeLayout;
    //优良选择按钮
    private RelativeLayout check_good_rela;
    //首页顶端两个按钮
    private ImageView home_title_remind, home_title_share;
    //污染物文字信息
    private TextView contaminated_text;
    //三种文字信息
    private TextView textlist_text;
    //明天两个时段天气
    private RelativeLayout today_weather_rela, contaminated_lvl;
    private TextView today_weather, tianqizhuangkuang, contaminated_lvl_text;
    private HourModel Hourmodel;
    private AqiModel aqiModel;
    private SixModel sixModel;
    private RelativeLayout tomorrow_weather_rela, contaminated_lvl_tomorrow;
    private TextView tomorrow_weather, tianqizhuangkuang_tomorrow, contaminated_lvl_tomorrow_text;
    private ZzWeatherView weatherView;//天气折线视图
    private ssWeatherView weatherViews;//天气折线视图
    private int getend = 0;
    private String city = Url.ADDRESSCITY;
    //    private String city ="四平市";
    public static boolean ischeck = false;

    @Override
    public void onResume() {
        super.onResume();
        if (ApiUtils.isNetworkConnected(getActivity()) && ischeck) {
            ApiUtils.windows(getActivity(), top_layout, "请稍后");
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    ApiUtils.closepopup();
                }
            }, 10000);
            if (!Url.LOGIN_TOKEN.equals(""))
                okHttp_postFromParametersa();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 300:
                if (ContextCompat.checkSelfPermission(getActivity(), locationPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予该权限，就去提示用户请求
                    Toast.makeText(getActivity(), "定位服务被禁止，位保证软件正常运行。请手动开起！", Toast.LENGTH_LONG).show();
                } else {
                    LunchActivity.locationManager.requestLocationUpdates("network", 0, 0, LunchActivity.myLocationListener);

                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            swipeLayout.setRefreshing(true);
                            city = Url.ADDRESSCITY;
                            okHttp_postFromParameters(0);
                            okHttp_postFromParameters(1);
                            okHttp_postFromParameters(2);
                            if (!Url.LOGIN_TOKEN.equals(""))
                                okHttp_postFromParametersa();
                            location_text.setText(city);
                        }
                    }, 1000);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 初始加载视图
     */
    public void InitView(View view) {
        swipeLayout.setRefreshing(true);
        //数据源s
        list = new ArrayList<>();
        lists = new ArrayList<>();
        okHttp_postFromParameters(0);
        okHttp_postFromParameters(1);
        okHttp_postFromParameters(2);
        if (!Url.LOGIN_TOKEN.equals(""))
            okHttp_postFromParametersa();
//        int titleheight = ApiUtils.getStatusBarHeight(getActivity());
//        swipeLayout.setPadding(0, titleheight, 0, 0);
        if (!Url.ADDRESSCITY.equals(""))
            location_text.setText(city);
        else
            location_text.setText("未能获取定位信息");
        location_text.setOnClickListener(this);
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeResources(android.R.color.holo_orange_dark,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        check_good_rela.setOnClickListener(this);
        home_title_remind.setOnClickListener(this);
        home_title_share.setOnClickListener(this);
        tomorrow_weather_rela.setOnClickListener(this);
        mCircleProgress1.setOnClickListener(this);
        today_weather_rela.setOnClickListener(this);
        int getshijian = ApiUtils.getmoning();
        if (getshijian == 0)
            top_layout.setBackground(getActivity().getDrawable(R.drawable.baitian));
        else
            top_layout.setBackground(getActivity().getDrawable(R.drawable.yewan));
        top_layout.setOnTouchListener(this);
        top_layout.setLongClickable(true);

        Map<String, Object> music = new HashMap<String, Object>();
        music.put("天气页面", "1");//自定义参数：音乐类型，值：流行
        MobclickAgent.onEventObject(getActivity(), "weather", music);
//                .setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                switch (event.getAction()) {
//
//                    case MotionEvent.ACTION_DOWN:
//                        mPosX = event.getX();
//                        mPosY = event.getY();
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        mCurPosX = event.getX();
//                        mCurPosY = event.getY();
//
//                        break;
//                    case MotionEvent.ACTION_UP:
////                        if (mCurPosY - mPosY > 0
////                                && (Math.abs(mCurPosY - mPosY) > 25)) {
////                            //向下滑動
////                            tiShi(mContext,"向下");
////
////                        } else if (mCurPosY - mPosY < 0
////                                && (Math.abs(mCurPosY - mPosY) > 25)) {
////                            //向上滑动
////                            tiShi(mContext,"向上");
////                        }
//                        if (mCurPosX - mPosX > 0
//                                && (Math.abs(mCurPosX - mPosX) > 25)) {

//                        } else if (mCurPosX - mPosX < 0
//                                && (Math.abs(mCurPosX - mPosX) > 25)) {

//                        }
//                        break;
//                }
//                return true;
//            }
//        });
    }

    private float mPosX, mPosY, mCurPosX, mCurPosY;


    public void nointe(View view) {
        top_layout = view.findViewById(R.id.top_layout);
        home_time = view.findViewById(R.id.home_time);
        swipeLayout = view.findViewById(R.id.swipe_container);
        location_text = view.findViewById(R.id.location_text);
        rc_time = view.findViewById(R.id.rc_time);
        rl_time = view.findViewById(R.id.rl_time);
        gif = view.findViewById(R.id.gif);
        mCircleProgress1 = view.findViewById(R.id.circle_progress_bar1);
        start_num_text = view.findViewById(R.id.start_num_text);
        end_num_text = view.findViewById(R.id.end_num_text);
        check_good_rela = view.findViewById(R.id.check_good_rela);
        home_title_remind = view.findViewById(R.id.home_title_remind);
        home_title_share = view.findViewById(R.id.home_title_share);
        contaminated_text = view.findViewById(R.id.contaminated_text);
        textlist_text = view.findViewById(R.id.textlist_text);
        today_weather_rela = view.findViewById(R.id.today_weather_rela);
        contaminated_lvl = view.findViewById(R.id.contaminated_lvl);
        today_weather = view.findViewById(R.id.today_weather);
        tianqizhuangkuang = view.findViewById(R.id.tianqizhuangkuang);
        contaminated_lvl_text = view.findViewById(R.id.contaminated_lvl_text);
        tianqi_good_text = view.findViewById(R.id.tianqi_good_text);
        tomorrow_weather_rela = view.findViewById(R.id.tomorrow_weather_rela);
        contaminated_lvl_tomorrow = view.findViewById(R.id.contaminated_lvl_tomorrow);
        tomorrow_weather = view.findViewById(R.id.tomorrow_weather);
        tianqizhuangkuang_tomorrow = view.findViewById(R.id.tianqizhuangkuang_tomorrow);
        contaminated_lvl_tomorrow_text = view.findViewById(R.id.contaminated_lvl_tomorrow_text);
        weatherView = view.findViewById(R.id.weather_view);
        weatherViews = view.findViewById(R.id.weather_views);
        mGestureDetector = new GestureDetector(getActivity(), myGestureListener);
        gettime(home_time);
        gif.setOnClickListener(this);
    }

    public void gettime(TextView v) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        v.setText("更新时间:" + simpleDateFormat.format(date));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.check_good_rela:

                break;
            case R.id.home_title_remind:
                Intent tomsg = new Intent(getActivity(), MsgListActivity.class);
                startActivity(tomsg, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
                break;
            case R.id.home_title_share:

                break;
            case R.id.today_weather_rela:

                break;
            case R.id.tomorrow_weather_rela:

                break;
            case R.id.circle_progress_bar1:
                Intent toxdw = new Intent(getActivity(), JianCeActivity.class);
                toxdw.putExtra("value", aqi + "");
                toxdw.putExtra("wuranwu", contaminated_text.getText());
                toxdw.putExtra("zhibiao", textlist_text.getText());
                toxdw.putExtra("pm10", PM10);
                toxdw.putExtra("pm25", PM2);
                toxdw.putExtra("no2", NO2);
                toxdw.putExtra("so2", SO2);
                toxdw.putExtra("co", CO);
                toxdw.putExtra("o3", O3);
                startActivity(toxdw, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
                break;
            case R.id.location_text:
                Intent tocity = new Intent(getActivity(), CityManageActivity.class);
                startActivity(tocity, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
                break;
            case R.id.gif:
                Intent tojiance = new Intent(getActivity(), JianCeListActivity.class);
                startActivity(tojiance, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
//                MainActivity.home_pager.setCurrentItem(2);
//                JianceFragment.kepu_list.setSelection(JianceFragment.kepu_list.getBottom());  ;
                break;
        }
    }

    public void weather() {
        //填充天气数据
        weatherView.setList(list);
        //画折线
        weatherView.setLineType(ZzWeatherView.LINE_TYPE_CURVE);
        //设置线宽
        weatherView.setLineWidth(4f);
        //点击某一列
        weatherView.setOnWeatherItemClickListener(new ZzWeatherView.OnWeatherItemClickListener() {
            @Override
            public void onItemClick(WeatherItemView itemView, int position, WeatherModel weatherModel) {
            }
        });
        weatherView.smoothScrollTo(0, 0);
    }

    public void login24hour() {
        //填充天气数据
        weatherViews.setList(lists);
        //画折线
        weatherViews.setLineType(ZzWeatherView.LINE_TYPE_CURVE);
        //设置线宽
        weatherViews.setLineWidth(4f);
        //点击某一列
        weatherViews.setOnWeatherItemClickListener(new ssWeatherView.OnWeatherItemClickListener() {
            @Override
            public void onItemClick(com.work.formaldehyde.zzweatherview.WeatherItemView itemView, int position, WeatherModels weatherModel) {
                int y = (int) (ApiUtils.HEIGHT - ApiUtils.HEIGHT * (weatherModel.getNightTemp() - ApiUtils.MIN_LINE) * 1.0f / (ApiUtils.MAX_LINE - ApiUtils.MIN_LINE)) + ApiUtils.TEXT_SIZE * 2;
                int x = ApiUtils.WIDTH;
                windows(getActivity(), itemView, "AQI:" + lists.get(position).getWindOrientation(), (y / 2) - 17);
            }
        });
        weatherViews.smoothScrollTo(0, 0);
    }


    private WeatherModel model;
    private WeatherModels models;
    private List<WeatherModels> lists;
    private List<WeatherModel> list;
    private int is = 0;

    private int isis = 0;
    ArrayList<String> cityary = new ArrayList<>();

    @Override
    public void onRefresh() {
        if (ContextCompat.checkSelfPermission(getActivity(), locationPermission[0]) != PackageManager.PERMISSION_GRANTED) {
            // 如果没有授予该权限，就去提示用户请求
            requestPermissions(locationPermission, 300);
        } else {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    int getshijian = ApiUtils.getmoning();
                    if (getshijian == 0)
                        top_layout.setBackground(getActivity().getDrawable(R.drawable.baitian));
                    else
                        top_layout.setBackground(getActivity().getDrawable(R.drawable.yewan));
                    lists.clear();
                    list.clear();
                    city = Url.ADDRESSCITY;
                    okHttp_postFromParameters(0);
                    okHttp_postFromParameters(1);
                    okHttp_postFromParameters(2);
                    if (!Url.LOGIN_TOKEN.equals(""))
                        okHttp_postFromParametersa();
                    location_text.setText(city);
                    swipeLayout.setRefreshing(false);
                    if (!Url.ADDRESSCITY.equals(""))
                        location_text.setText(city);
                    else
                        location_text.setText("未能获取定位信息");
                    gettime(home_time);
                }
            }, 3000);
        }
    }

    //    private void okHttp_postFromParametersa() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID)
//                            .build();
//                    Request request = new Request.Builder().url(Url.GETCITYLIST).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    gets.sendMessage(message);
//                } catch (
//                        Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }).
//                start();
//    }
    private void okHttp_postFromParametersa() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder().get().url(Url.GETCITYLISTS+ Url.USER_ID + "&logintoken=" + Url.LOGIN_TOKEN).build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                gets.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    private CityManageModel cityManageModel;
    public Handler gets = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        ischeck = false;
                        Gson gson = new Gson();
                        cityManageModel = gson.fromJson(msg.obj.toString(),
                                CityManageModel.class);
                        cityary.clear();
                        for (int i = 0; i < cityManageModel.data.size(); i++) {
                            cityary.add(cityManageModel.data.get(i).getCity_name());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    public void windows(Context context, View view, String apistr, int y) {
        BubbleLayout bl = new BubbleLayout(context);
        bl.setBubbleColor(getResources().getColor(R.color.bubble_color));
        View popupwindowview = LayoutInflater.from(context).inflate(
                R.layout.window_bubble, null);
        TextView item_bubble = popupwindowview.findViewById(R.id.item_bubble);
        item_bubble.setText(apistr);
        new BubbleDialog(context)
                .addContentView(popupwindowview)
                .setClickedView(view)
                .calBar(true).setOffsetY(y).setTransParentBackground()
                .setBubbleLayout(bl)
                .show();
    }

//    private void okHttp_postFromParameters(final int i) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    OkHttpClient okHttpClient = new OkHttpClient();
//                    if (i == 0) {
//                        RequestBody formBody = new FormBody.Builder().add("city", city)
//                                .build();
////                        Request request = new Request.Builder().url(Url.ADDRESSTIANQI).post(formBody).build();
//                        Request request = new Request.Builder().url(Url.KONGQIZHILIANG).post(formBody).build();
//                        okhttp3.Response response = okHttpClient.newCall(request).execute();
//                        String msg = response.body().string();
//                        JSONObject success_Object = new JSONObject(msg);
//                        String code = success_Object.getString("code");
//                        date = success_Object.getString("data");
//                        if (code.equals("1")) {
//                            JSONObject Object = new JSONObject(date);
//                            Message message = new Message();
//                            message.obj = date;
//                            gethot.sendMessage(message);
//                        }
//                    } else if (i == 1) {
//                        RequestBody formBody = new FormBody.Builder().add("city", city)
//                                .build();
//                        Request request = new Request.Builder().url(Url.MEIXIAOSHITIANQI).post(formBody).build();
//                        okhttp3.Response response = okHttpClient.newCall(request).execute();
//                        String msg = response.body().string();
//                        Message message = new Message();
//                        message.obj = msg;
//                        gethot1.sendMessage(message);
//                    } else {
//                        RequestBody formBody = new FormBody.Builder().add("city", city)
//                                .build();
//                        Request request = new Request.Builder().url(Url.YIZHOUTIANQI).post(formBody).build();
//                        okhttp3.Response response = okHttpClient.newCall(request).execute();
//                        String msg = response.body().string();
//                        Message message = new Message();
//                        message.obj = msg;
//                        gethot2.sendMessage(message);
//                    }
//                } catch (
//                        Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }).
//                start();
//    }

    private void okHttp_postFromParameters(final int i) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    if (i == 0) {
                        Request request = new Request.Builder().get().url(Url.KONGQIZHILIANG + city).build();
                        Call call = okHttpClient.newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                            }

                            @Override
                            public void onResponse(Call call, final Response response) {
                                try {
                                    final String responseStr;
                                    responseStr = response.body().string();
                                    Message message = new Message();
                                    message.obj = responseStr;
                                    gethot.sendMessage(message);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } else if (i == 1) {
                        Request request = new Request.Builder().get().url(Url.TODAYAQI + city).build();
                        Call call = okHttpClient.newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                            }

                            @Override
                            public void onResponse(Call call, final Response response) {
                                try {
                                    final String responseStr;
                                    responseStr = response.body().string();
                                    Message message = new Message();
                                    message.obj = responseStr;
                                    gethot1.sendMessage(message);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } else {
                        Request request = new Request.Builder().get().url(Url.WEEKAQI + city).build();
                        Call call = okHttpClient.newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                            }

                            @Override
                            public void onResponse(Call call, final Response response) {
                                try {
                                    final String responseStr;
                                    responseStr = response.body().string();
                                    Message message = new Message();
                                    message.obj = responseStr;
                                    gethot2.sendMessage(message);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    private String PM10, PM2, NO2, CO, SO2, O3;

    public Handler gethot = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    gettime(home_time);
                    swipeLayout.setRefreshing(false);
                    Gson gson = new Gson();
                    aqiModel = gson.fromJson(msg.obj.toString(),
                            AqiModel.class);
                    aqi = aqiModel.data.getAqi();
                    pm25 = aqiModel.data.getPm25();
                    humidity = aqiModel.data.getHumidity();
                    wind_speed = aqiModel.data.getWind_speed();
                    temperature = aqiModel.data.getTemperature();
                    primary_pollutant = aqiModel.data.getPrimary_pollutant();
                    quality = aqiModel.data.getQuality();
                    PM10 = aqiModel.data.getPm10();
                    PM2 = aqiModel.data.getPm25();
                    NO2 = aqiModel.data.getNo2();
                    CO = aqiModel.data.getCo();
                    SO2 = aqiModel.data.getSo2();
                    O3 = aqiModel.data.getO3();
                    start_num_text.setText(Hourmodel.getData().getHours().get(0).getAqi() + "");
                    int aqis = Integer.parseInt(aqi);
                    mCircleProgress1.setValue(Integer.parseInt(Hourmodel.getData().getHours().get(0).getAqi()));
                    textlist_text.setText("温度：" + temperature + "℃\t\t\t湿度：" + humidity + "%\t\t\t风力：" + wind_speed + "km/h");
                    if (primary_pollutant.equals("null"))
                        contaminated_text.setText("无污染物");
                    else
                        contaminated_text.setText("首要污染物：" + primary_pollutant);
                    tianqi_good_text.setText(quality);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public Handler gethot1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    swipeLayout.setRefreshing(false);
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        Hourmodel = gson.fromJson(msg.obj.toString(),
                                HourModel.class);
                        rc_time.setText(Hourmodel.getData().getSun().getSunrise());
                        rl_time.setText(Hourmodel.getData().getSun().getSunset());
                        for (int i = 0; i < Hourmodel.getData().getHours().size(); i++) {
                            isis = i;
                            String tq = "多云";
                            if (i % 2 == 0) {
                                isis = 0;
                                tq = "小雨";
                            }
                            models = new WeatherModels();
                            models.setDayTemp(isis); //白天温度
                            models.setNightTemp(Integer.parseInt(Hourmodel.getData().getHours().get(i).getAqi())); //温度折线
                            models.setNightWeather(tq); //修改图标
                            models.setTianqitext(Hourmodel.getData().getHours().get(i).getTemperature() + "°"); //天气text
                            models.setWindOrientation(Hourmodel.getData().getHours().get(i).getAqi()); //级别
                            models.setWindLevel(Hourmodel.getData().getHours().get(i).getTime()); //
                            if (Hourmodel.getData().getHours().get(i).getQuality().equals("优"))
                                models.setAirLevel(AirLevel.EXCELLENT);
                            else if (Hourmodel.getData().getHours().get(i).getQuality().equals("良"))
                                models.setAirLevel(AirLevel.GOOD);
                            else if (Hourmodel.getData().getHours().get(i).getQuality().equals("轻度污染"))
                                models.setAirLevel(AirLevel.LIGHT);
                            else if (Hourmodel.getData().getHours().get(i).getQuality().equals("中度污染"))
                                models.setAirLevel(AirLevel.MIDDLE);
                            else if (Hourmodel.getData().getHours().get(i).getQuality().equals("重度污染"))
                                models.setAirLevel(AirLevel.HIGH);
                            else
                                models.setAirLevel(AirLevel.POISONOUS);
                            lists.add(models);
                        }
                        start_num_text.setText(Hourmodel.getData().getHours().get(0).getAqi() + "");
                        mCircleProgress1.setValue(Integer.parseInt(Hourmodel.getData().getHours().get(0).getAqi()));
                        login24hour();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public String getweek(int i) {
        switch (i) {
            case 1:
                return "周日";
            case 2:
                return "周一";
            case 3:
                return "周二";
            case 4:
                return "周三";
            case 5:
                return "周四";
            case 6:
                return "周五";
            case 7:
                return "周六";
        }
        return "周一";
    }

    public Handler gethot2 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    swipeLayout.setRefreshing(false);
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        sixModel = gson.fromJson(msg.obj.toString(),
                                SixModel.class);
                        for (int i = 0; i < sixModel.getData().size(); i++) {
                            model = new WeatherModel();
                            String str = sixModel.getData().get(i).getDate();
                            String str1 = str.substring(5, str.length());
                            model.setDate(str1);//日期
                            if (i == 0)
                                model.setWeek("昨天");
                            else if (i == 1)
                                model.setWeek("今天");
                            else if (i == 2)
                                model.setWeek("明天");
                            else
                                model.setWeek(getweek(ApiUtils.getDayofWeek(str)));
                            model.setDayWeather(sixModel.getData().get(i).getHigh() + "°"); //白天天气
                            model.setGetwendu("12" + i);
                            model.setLinecolor(R.color.back_view);
                            model.setDayTemp(Integer.parseInt(sixModel.getData().get(i).getHigh())); //白天温度
                            model.setNightTemp(Integer.parseInt(sixModel.getData().get(i).getLow())); //夜晚温度
                            model.setNightWeather(sixModel.getData().get(i).getText_day()); //夜晚天气
                            model.setNightWeathers(sixModel.getData().get(i).getAqi_max() + ""); //夜晚天气
                            model.setWindOrientation("PM" + is); //风向
                            model.setWindLevel(sixModel.getData().get(i).getText_day()); //
                            list.add(model);
                        }
                        today_weather.setText(sixModel.getData().get(2).getLow() + "℃~" + sixModel.getData().get(2).getHigh() + "℃");
                        tomorrow_weather.setText(sixModel.getData().get(3).getLow() + "℃~" + sixModel.getData().get(3).getHigh() + "℃");
                        tianqizhuangkuang.setText(sixModel.getData().get(2).getText_day());
                        tianqizhuangkuang_tomorrow.setText(sixModel.getData().get(3).getText_day());
                        int getValue = Integer.parseInt(sixModel.getData().get(2).getAqi_max());
                        int getValues = Integer.parseInt(sixModel.getData().get(2).getAqi_max());
                        if (getValue >= 0 && getValue <= 50) {
                            contaminated_lvl.setBackgroundResource(R.color.contaminated_green);
                            contaminated_lvl_text.setText("优");
                        } else if (getValue >= 51 && getValue <= 100) {
                            contaminated_lvl.setBackgroundResource(R.color.contaminated_yellow);
                            contaminated_lvl_text.setText("良");
                        } else if (getValue >= 101 && getValue <= 150) {
                            contaminated_lvl.setBackgroundResource(R.color.contaminated_orange);
                            contaminated_lvl_text.setText("轻度");
                        } else if (getValue >= 151 && getValue <= 200) {
                            contaminated_lvl.setBackgroundResource(R.color.contaminated_red);
                            contaminated_lvl_text.setText("中度");
                        } else if (getValue >= 201 && getValue <= 300) {
                            contaminated_lvl.setBackgroundResource(R.color.contaminated_violet);
                            contaminated_lvl_text.setText("重度");
                        } else {
                            contaminated_lvl.setBackgroundResource(R.color.contaminated_vermilion);
                            contaminated_lvl_text.setText("严重");
                        }
                        if (getValues >= 0 && getValues <= 50) {
                            contaminated_lvl_tomorrow.setBackgroundResource(R.color.contaminated_green);
                            contaminated_lvl_tomorrow_text.setText("优");
                        } else if (getValues >= 51 && getValues <= 100) {
                            contaminated_lvl_tomorrow.setBackgroundResource(R.color.contaminated_yellow);
                            contaminated_lvl_tomorrow_text.setText("良");
                        } else if (getValues >= 101 && getValues <= 150) {
                            contaminated_lvl_tomorrow.setBackgroundResource(R.color.contaminated_orange);
                            contaminated_lvl_tomorrow_text.setText("轻度");
                        } else if (getValues >= 151 && getValues <= 200) {
                            contaminated_lvl_tomorrow.setBackgroundResource(R.color.contaminated_red);
                            contaminated_lvl_tomorrow_text.setText("中度");
                        } else if (getValues >= 201 && getValues <= 300) {
                            contaminated_lvl_tomorrow.setBackgroundResource(R.color.contaminated_violet);
                            contaminated_lvl_tomorrow_text.setText("重度");
                        } else {
                            contaminated_lvl_tomorrow.setBackgroundResource(R.color.contaminated_vermilion);
                            tianqizhuangkuang.setText("严重");
                        }
                        weather();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };


    private static final int FLING_MIN_DISTANCE = 50;   //最小距离
    private static final int FLING_MIN_VELOCITY = 0;  //最小速度

    GestureDetector.SimpleOnGestureListener myGestureListener = new GestureDetector.SimpleOnGestureListener() {
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            float x = e1.getX() - e2.getX();
            float x2 = e2.getX() - e1.getX();
            if (x > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
                if (cityary.size() > 0 && cityindex < (cityary.size() - 1)) {
                    if (ApiUtils.isNetworkConnected(getActivity())) {
                        cityindex++;
                        lists.clear();
                        list.clear();
                        city = cityary.get(cityindex);
                        location_text.setText(city);
                        ApiUtils.windows(getActivity(), top_layout, "切换中");
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                ApiUtils.closepopup();
                            }
                        }, 10000);
                        okHttp_postFromParameters(0);
                        okHttp_postFromParameters(1);
                        okHttp_postFromParameters(2);
                        if (!Url.LOGIN_TOKEN.equals(""))
                            okHttp_postFromParametersa();
                    }
                }
            } else if (x2 > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
                if (cityindex > -1 && cityary.size() > 0) {
                    if (ApiUtils.isNetworkConnected(getActivity())) {
                        cityindex--;
                        lists.clear();
                        list.clear();
                        if (cityindex == -1) {
                            city = Url.ADDRESSCITY;
                        } else {
                            city = cityary.get(cityindex);
                        }
                        location_text.setText(city);
                        ApiUtils.windows(getActivity(), top_layout, "切换中");
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                ApiUtils.closepopup();
                            }
                        }, 10000);
                        okHttp_postFromParameters(0);
                        okHttp_postFromParameters(1);
                        okHttp_postFromParameters(2);
                        if (!Url.LOGIN_TOKEN.equals(""))
                            okHttp_postFromParametersa();
                    }
                }
            }
            return false;
        }
    };
    private GestureDetector mGestureDetector;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }
}